<?php

/**

 * 后台首页
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Home\Controller;

use Think\Controller;

class IndexController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        $this->limit = 10;

        //获取流程分类
        $sorts = M('flow_sort')->where('sort_no != 0')->order('sort_no')->select();
        $this->sorts = $sorts;

        //判断用户是否可以提出问题与建议
        $handleUser = array('qiaoshoujuan', 'zhangyingheng', 'zhoulingling', '1213');
        if (in_array(session('user_id'), $handleUser)) {
            $is_handle = 1;
        } else {
            $is_handle = 0;
    }
        $this->is_handle = $is_handle;
    }

    //首页
    public function index() {
        //在线人数
        $this->onlineCount = M('user')->where('is_online=1')->count();
        //在线用户
        $this->onlineUser = M('user')->field('user_id,user_name,dept_id,head,head_url')->where('is_online=1')->select();

        //快速导航
        $this->qNavs = M('backmenu')->where('nav_name != ""')->order('nav_no')->select();

        //获取图片新闻
        $this->imgNews = M('news')->field('news_id,subject,provider,news_time,CLICK_COUNT,uploads,uploads_url')->where('is_show = 1')->order('news_time desc')->select();

        //获取最新的6条新闻
        $news = M('news')->field('news_id,subject,provider,news_time,readers')->where('is_show = 0')->order('news_time desc')->limit(6)->select();
        foreach ($news as $key => $row) {
            if (strpos($row['readers'], session('user_id')) === false || (empty($row['readers']))) {
                $news[$key]['noRead'] = 1;
            }
            $news[$key]['news_time'] = substr($row['news_time'], 0, 10);
        }
        $this->news = $news;

        //获取最新的6条通知
        $notifys = M('notify')->field('notify_id,subject,audit_date,readers')->order('audit_date desc')->limit(6)->select();
        $notifyNoRead = 0;
        foreach ($notifys as $key => $row) {
            if (strpos($row['readers'], session('user_id')) === false || (empty($row['readers']))) {
                $notifys[$key]['noRead'] = 1;
                $notifyNoRead++;
            } else {
                $notifys[$key]['noRead'] = 0;
            }
        }
        $this->notifys = $notifys;
        //最新动态--公告通知数
        $this->notifyNoRead = $notifyNoRead;

        //待办流程数量
        $this->runCount = count($this->getLists(1, 0, 1, ''));

        //获取5条待办流程
        $runs = $this->getLists(1, 5, 1, '');
        foreach ($runs as $key => $row) {
            $runs[$key]['date'] = substr($row['create_time'], 0, 10);
            //去run_name中的时间
            $start = strpos($row['run_name'], '(');
            if ($start !== false) {
                $runs[$key]['run_name'] = substr($row['run_name'], 0, $start);
            }
        }
        $this->runs = $runs;

        //获取5条待办计划
        unset($map);
        $map['sms_flag'] = 0;
        $where['executor'] = array('like', '%' . session('user_id') . '%');
        $where['manager'] = array('like', '%' . session('user_id') . '%');
        $where['participator'] = array('like', '%' . session('user_id') . '%');
        $where['creator'] = session('user_id');
        $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
        $where['opinion_leader'] = array('like', '%' . session('user_id') . '%');
        $where['_logic'] = 'or';
        $map['_complex'] = $where;
        $plans = M('work_plan')->where($map)->order('begin_date desc,level desc')->limit(5)->select();
        $this->plans = $plans;

        //        print_r($plans);
        //获取未完成计划条数
//        $lists = $this->getPlanData(0);
//        $count = count($lists);
//        $this->unfinishedCount = $count;
//        $this->unfinishReaderNumber = $lists[0]['readNum'];
//
//        //获取已完成的计划条数
//        $lists = $this->getPlanData(1);
//        $count = count($lists);
//        $this->finishCount = $count;
//        $this->finishReaderNumber = $lists[0]['readNum'];
//
//        //我的计划数
//        $lists = $this->planLists(0);
//        $this->allCount = count($lists);
//        $this->myPlanReadNumber = $lists[0]['readNum'];
//
//        //我关注的计划数
//        $lists = $this->planLists(1);
//        $this->followCount = count($lists);
//        $this->followReadNumber = $lists[0]['readNum'];
        //判断用户角色
        //公司领导
//        $pMap['PRIV_NO'] = array('elt', 20);
//        $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
//        if (in_array(session('user_priv'), $privIds)) {
//            //公司领导
//            $userPriv = 'comLeader';
//            $this->leaderProcessDetail = $this->leaderProcessDetail($planTypes);    //公司领导获取所有部门总计划百分比
//        } else {
//            //部门领导
//            $pMap['PRIV_NO'] = array('between', [30, 40]);
//            $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
//            if (in_array(session('user_priv'), $privIds)) {
//                $userPriv = 'deptLeader';
//            } else {
//                $userPriv = 'user';
//            }
//        }
//        $this->userPriv = $userPriv;
        //获取计划类型
        $planTypes = M('plan_type')->where('pid = 0')->order('type_no')->select();
//        $this->userPercents = $this->userProcessDetail($planTypes); //个人按类型完成计划百分比(员工和公司领导)
//        print_r($this->leaderProcessDetail);
        //按类型获取和我相关5条最新计划
        unset($map);
        unset($where);
        $where['manager'] = session('user_id');
        $where['participator'] = array('like', '%' . session('user_id') . '%');
        $where['executor'] = array('like', '%' . session('user_id') . '%');
        $where['creator'] = session('user_id');
        $where['_logic'] = 'or';
//        $map['_string'] = 'TO_ID like "%' . session('dept_id') . '%" or TO_ID = null';
        $map['sms_flag'] = 0;
        $planNoRead = 0;
        foreach ($planTypes as $key => $row) {
            $map['type'] = $row['type_id'];
            $map['_complex'] = $where;
            $myPlans = M('work_plan')->where($map)->order('create_date desc')->limit(5)->select();
            foreach ($myPlans as $p_key => $p_row) {
                //增加未读标记
                $readArr = explode(',', $p_row['reader']);
                if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                    $myPlans[$p_key]['noRead'] = 1;
                    //最新动态--工作计划数
                    $planNoRead++;
                } else {
                    $myPlans[$p_key]['noRead'] = 0;
                }
            }
            $planTypes[$key]['plans'] = $myPlans;
        }
        $this->planNoRead = $planNoRead;
        $this->planTypes = $planTypes;

        //最新动态--新闻动态数
        $news = M('news')->field('news_id,readers')->where('is_show = 0')->order('news_time desc')->select();
        $newsNoRead = 0;
        foreach ($news as $key => $row) {
            if (strpos($row['readers'], session('user_id')) === false || (empty($row['readers']))) {
                $newsNoRead ++;
            }
        }
        $this->newsNoRead = $newsNoRead;

        //最新动态--假期结余数
        $userinfo = M('userinfo')->where('user_id="' . session('user_id') . '"')->find();
        $this->vacation = $userinfo['able_year'] + $userinfo['able_vacation'];

        //获取新邮件数量
        $userid = M('user')->where('user_id="' . session('user_id') . '"')->getField('email');
        $result = getNewExmailCount($userid);
        if ($result['status'] == 1) {
            $this->newCount = $result['count'];
        }

        //获取三条日程
//        $cMap['user_id'] = session('user_id');
        $cMap['status'] = 0;
        $cMap['_string'] = 'user_id = "'.session('user_id').'" or create_user = "'.session('user_id').'" and end_time = 0 or end_time >'.time();
        $this->calendars = M('calendar')->field('id,user_id,title,content,remind_time,create_user')->where($cMap)->order('start_time desc,remind_time asc')->select();

        $this->user_id = session('user_id');
        $this->title = '后台首页';
        $this->display();
    }

    //单点登录企业邮箱
    public function loginEamil() {
        $userid = M('user')->where('user_id="' . session('user_id') . '"')->getField('email');
        $result = loginExmail($userid);
        if ($result['status'] == 1) {
            $data['email_url'] = $result['url'];
            $this->ajaxReturn($result['url']);
        } else {
            $this->ajaxReturn(false);
        }
    }

    //获取计划未完成、已完成数
    public function getEchartsData() {
        //公司领导
        $pMap['priv_no'] = array('elt', 20);
        $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
        if (in_array(session('user_priv'), $privIds)) {
            //公司领导：所有部门当月计划
        } else {
            $pMap['priv_no'] = array('between', [30, 40]);
            $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
            if (in_array(session('user_priv'), $privIds)) {
                //部门领导
                $where['executor'] = array('like', '%' . session('user_id') . '%');
                $where['manager'] = array('like', '%' . session('user_id') . '%');
                $where['participator'] = array('like', '%' . session('user_id') . '%');
                $where['creator'] = session('user_id');
                $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
                $where['_string'] = 'TO_ID like "%' . session('dept_id') . '%"';
                $where['_logic'] = 'or';
            } else {
                //员工
                $where['executor'] = array('like', '%' . session('user_id') . '%');
                $where['manager'] = array('like', '%' . session('user_id') . '%');
                $where['participator'] = array('like', '%' . session('user_id') . '%');
                $where['creator'] = session('user_id');
                $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
                $where['_logic'] = 'or';
            }
        }

        $sDate = date('Y') . '-' . (date('m') - 1) . '-24';
        $eDate = date('Y-m-23');
        $map['_string'] = 'begin_date >= "' . date('Y-01-01') . '" and (end_date <= "' . $eDate . '" or end_date = "0000-00-00")';
        $map['_complex'] = $where;
        $map['sms_flag'] = 0;

        //获取未完成计划条数
        $lists = $this->getPlanData('', 0, $map);
        $count = count($lists);
        $data[0]['value'] = $count;
        $data[0]['name'] = '未完成';

        //获取已完成的计划条数
        $map['_string'] = 'begin_date >= "' . $sDate . '" and (end_date <= "' . $eDate . '" or end_date = "0000-00-00")';
        $map['sms_flag'] = 1;
        $lists = $this->getPlanData('', 0, $map);
        $count = count($lists);
        $data[1]['value'] = $count;
        $data[1]['name'] = '已完成';

        $this->ajaxReturn($data);
    }

    //获取天气
    public function getWather() {
        $map['create_date'] = date('Y-m-d');
        $row = M('wather')->where($map)->find();

        if ($row) {
            $result = json_decode($row['content']);
        } else {
            $ip = the_public_ip();
            $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
            $ip = json_decode(file_get_contents($url));
            if ((string) $ip->code == '1') {
                $city = '';
            } else {
                $data = (array) $ip->data;
                $city = $data['city'];
            }

            $url = 'https://www.sojson.com/open/api/weather/json.shtml?city=' . urlencode($city);
            $result = json_decode(file_get_contents($url));
            if ($result->status == 200) {
                //存入wather表
                $wdata['create_date'] = date('Y-m-d');
                $wdata['content'] = json_encode($result);
                M('wather')->add($wdata);
            }
        }

        $wather['city'] = $result->city;
        $wather['type'] = $result->data->forecast[0]->type;

        $map['type'] = array('like', '%' . $wather['type'] . '%');
        $wather['icon'] = M('wather_icon')->where($map)->getField('icon');

        $high = $result->data->forecast[0]->high;
        $low = $result->data->forecast[0]->low;
        $start = strpos($low, ' ') + 1;
        $end = strpos($low, '.');
        $wather['low'] = substr($low, 0, 9);
        $start = strpos($wather['low'], ' ') + 1;
        $wather['low'] = substr($wather['low'], $start);
        $start = strpos($high, ' ') + 1;
        $wather['high'] = substr($high, $start);

        $forecast = $result->data->forecast;
        foreach ($forecast as $key => $row) {
            if ($key != 0 && $key < 4) {
                $start = strpos($row->low, ' ') + 1;
                $end = strpos($row->low, '.');
                $low = substr($row->low, 0, 9);
                $start = strpos($low, ' ') + 1;
                $low = substr($low, $start);
                $wather['after'][$key - 1]['low'] = $low;
                $start = strpos($row->high, ' ') + 1;
                $wather['after'][$key - 1]['high'] = substr($row->high, $start);
                $wather['after'][$key - 1]['type'] = $row->type;
                $map['type'] = array('like', '%' . $row->type . '%');
                $wather['after'][$key - 1]['icon'] = M('wather_icon')->where($map)->getField('icon');
                $wather['after'][$key - 1]['date'] = $row->date;
            }
        }

        $this->ajaxReturn($wather);
    }

    /*
     * 获取计划列表
     * param $type  0进行中 1已完结 ''所有
     * param $limit 取几条，空取全部
     * return array
     */

    private function getPlanData($type = '', $limit = 0, $map = '') {
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);

        if (!$map) {
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['manager'] = array('like', '%' . session('user_id') . '%');
            $where['participator'] = array('like', '%' . session('user_id') . '%');
            $where['creator'] = session('user_id');
            $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
            $where['opinion_leader'] = array('like', '%' . session('user_id') . '%');
//            $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
//            $where['TO_ID'] = array('like', '%' . session('dept_id_other') . '%');
            $where['_string'] = ' to_id = "" or to_id like "%' . session('dept_id') . '%"';
            if (session('dept_id_other')) {
                $where['_string'] .= ' or to_id like "%' . session('dept_id_other') . '%" or to_id = ""';
            }
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }

        if ($map[0] == 'all') {
            $map = '';
        }

        if ($type !== '') {
            if ($type == 1) {
                $map['sms_flag'] = 1;
                $map['end_date'] = array('lt', date('Y-m-d'));
            } else {
                $map['sms_flag'] = 0;
            }
        }

        if ($limit) {
            $lists = M('work_plan')->where($map)->order('level asc,end_date desc,begin_date desc')->limit($start, $limit)->select();
        } else {
            $lists = M('work_plan')->where($map)->order('level asc,end_date desc,begin_date desc')->select();
        }

//        echo M('work_plan')->_sql();die;
        $readCount = 0;
        foreach ($lists as $key => $row) {
            $lists[$key]['manager_name'] = getMoreUsername($row['manager']);
            $lists[$key]['participator_name'] = getMoreUsername($row['participator']);
            $lists[$key]['status'] = $row['sms_flag'] ? '<font color="red">已结束</font>' : '<font color="green">进行中</font>';

            //标记新进度计划条数
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $readCount++;
            }
        }
        if (!empty($lists)) {
            $lists[0]['readNum'] = $readCount;
        }

        return $lists;
    }

    /* 用户相关的计划条数
     * param   $type    1:关注的计划   0：和我相关的计划
     * return   int
     */

    public function planLists($type) {
        if ($type == 1) {
            //关注的计划数
            $map['follow_user'] = array('like', '%' . session('user_id') . "%");
            $plan = M('work_plan')->where($map)->select();
        } else {
            //全部计划
            //取进行中的当月计划,
            $map['sms_flag'] = 0;
            //$map['_string'] = ' begin_date between "' . date('Y-m-01') . '" and "' . date('Y-m-31') . '" or end_date between "' . date('Y-m-01') . '" and "' . date('Y-m-31') . '" or end_date = "0000-00-00"';
            $leaderId = M('department')->where('DEPT_NAME = "公司领导"')->getField('dept_id');
            if (session('dept_id') == $leaderId) {
                $counts = M('plan_type')->where('pid = 0')->order('type_no')->select();

                foreach ($counts as $key => $row) {
                    $map['type'] = $row['type_id'];
                    $datas[] = M('work_plan')->where($map)->select();
                }
                $plan = $this->array2D($datas);
            } else {
                //当前用户全部的周计划
                $where['executor'] = array('like', '%' . session('user_id') . '%');
                $where['manager'] = array('like', '%' . session('user_id') . '%');
                $where['participator'] = array('like', '%' . session('user_id') . '%');
                $where['creator'] = session('user_id');
                $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
                $where['opinion_leader'] = array('like', '%' . session('user_id') . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $plan = M('work_plan')->where($map)->select();
            }
        }

        //加未读进度数
        $readCount = 0;
            foreach ($plan as $key => $value) {
                $readArr = explode(',', $value['reader']);
                if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                    $readCount++;
                    $plan[$key]['noread'] = 1;
                }
            }
            $plan[0]['readNum'] = $readCount;

        return $plan;
    }

    public function lists() {
        //获取sort_no=1的流程 
        $map['flow_sort'] = $this->sorts[0]['sort_id'];
        $flows = M('flow_type')->field('flow_id,flow_name,form_id,flow_sort,flow_no,is_show,icon,color')->where($map)->order('flow_no')->select();

        $this->flows = $flows;

        //修改菜单mid
        $this->mid = M('backmenu')->where('name="修改流程信息"')->getField('id');

        $this->display();
    }

    public function save() {
        if (IS_POST) {
            $data = I('post.');
            $sdata['flow_name'] = $data['flow_name'];
            $sdata['flow_sort'] = $data['flow_sort'];
            $sdata['flow_no'] = $data['flow_no'];
            $sdata['is_show'] = $data['is_show'];
            $sdata['icon'] = $data['icon'];
            $sdata['color'] = $data['color'];
            $map['flow_id'] = $data['id'];
            $res = M('flow_type')->where($map)->save($sdata);
            if ($res !== false) {
                $return['info'] = '保存成功';
                $return['url'] = U('lists');
            }
            $this->ajaxReturn($return);
        }

        $row = M('flow_type')->where('flow_id=' . I('id'))->find();
        $this->info = $row;
        $this->display();
    }

    public function getFlowSort() {
        $id = I('id');
        $data = M('flow_type')->field('flow_id,flow_name,form_id,flow_sort,flow_no,is_show,icon,color')->where('flow_sort=' . $id)->order('flow_no')->select();
        $this->ajaxReturn($data);
    }

    //菜单管理
    public function backmenu() {
        if (isset($_GET['name']) && I('name')) {
            $map['name'] = array('like', '%' . I('name') . '%');
            $this->name = I('name');
        }
        $p = I('get.p', 1, 'intval');
        $limit = $this->limit;

        $data = M('backmenu')->where($map)->order('pid asc,sort asc')->page($p, $limit)->select();

        $this->count = M('backmenu')->where($map)->count();
        $this->page = $this->pageLists($this->count, $limit);

        //修改菜单mid
        $this->mid = M('backmenu')->where('name="修改菜单"')->getField('id');

        $this->data = $data;
        $this->display();
    }

    //修改菜单
    public function saveBackmenu() {
        if (IS_AJAX) {
            $data = I('post.');
            if ($data['id']) {
                $res = M('backmenu')->save($data);

                $menuId = $data['id'];
//                $sData['url'] = explode('?', $data['url'])[0] . '?mid=' . $menuId;
            } else {
                $res = M('backmenu')->add($data);

                $menuId = $res;
//                $sData['url'] = $data['url'] . '?mid=' . $menuId;
            }
            //修改url 加id
            $mMap['id'] = $menuId;
            M('backmenu')->where($mMap)->save($sData);

            if ($res !== false) {
                $return['info'] = '提交成功';
                $return['url'] = U('backmenu');
            } else {
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }

        //获取上级菜单
        $this->tops = M('backmenu')->where('pid = 0')->order('sort')->select();

        if (I('id')) {
            $this->info = M('backmenu')->find(I('id'));
        }


        $this->display();
    }

    //权限管理
    public function role() {
        $p = I('get.p', 'intval', 0);
        $limit = 15;
        $roles = M('user_priv')->order('priv_no')->page($p, $limit)->select();
        foreach ($roles as $key => $row) {
            $map['id'] = array('in', explode(',', $row['menu_id']));
            $roleNames = M('backmenu')->where($map)->getField('name', true);
            if ($roleNames && (!is_array($roleNames))) {
                $roleNames[] = $roleNames;
            }
            $roles[$key]['menu_name'] = implode(', ', $roleNames);
        }

        $count = M('user_priv')->count();
        $this->page = $this->pageLists($count, $limit);

        //修改菜单mid
        $this->mid = M('backmenu')->where('name="修改权限"')->getField('id');

        $this->datas = $roles;
        $this->display();
    }

    //权限修改
    public function saveRole() {
        if (IS_AJAX) {
            $data['menu_id'] = implode(',', I('menu_id'));
            $flag = true;
            if (I('id')) {
                $map['user_priv'] = I('id');
                $res = M('user_priv')->where($map)->save($data);
            } else {
                $data['priv_name'] = I('priv_name');
                $data['priv_no'] = I('priv_no');
                $row = M('user_priv')->where('priv_name = "' . I('priv_name') . '"')->count();
                if ($row) {
                    $flag = false;
                    $return['info'] = '该角色已存在，请务重复创建';
                    $return['status'] = 0;
                } else {
                    $res = M('user_priv')->add($data);
                }
            }

            if ($flag == true) {
                if ($res !== false) {
                    $return['info'] = '操作成功';
                    $return['status'] = 1;
                    $return['url'] = U('role');
                    $return['icon'] = 6;
                } else {
                    $return['info'] = '操作失败';
                    $return['status'] = 0;
                    $return['icon'] = 5;
                }
            }
            $this->ajaxReturn($return);
        }

        if (I('id')) {
            $info = M('user_priv')->where('user_priv=' . I('id'))->find();
            $info['menuIds'] = explode(',', $info['menu_id']);
        }

        //获取菜单
        $menus = M('backmenu')->where('pid = 0')->order('sort')->select();
        foreach ($menus as $key => $row) {
            $menus[$key]['child'] = M('backmenu')->where('pid=' . $row['id'])->order('sort')->select();
        }

        $this->id = I('id');
        $this->menus = $menus;
        $this->info = $info;
        $this->display();
    }

    /*
     * ajax获取部门领导个人及部门计划百分比（部门领导视图）
     */

    public function getDeptPlanPercent() {
        //获取个人计划进展
        $planTypes = M('plan_type')->where('pid = 0')->order('type_no')->select();
        $userPercents = $this->userProcessDetail($planTypes);
        foreach ($userPercents as $key => $row) {
            $return['type'][] = $row['name'];
            $return['userPercent'][] = $row['total'];
            $return['userNumber'][] = substr($row['total'], 0, -1);
        }

        //获取部门计划进展
        $deptPercents = $this->getDeptPercent();
        foreach ($deptPercents as $key => $row) {
            foreach ($userPercents as $u_key => $u_row) {
                if ($row['type'] == $u_row['name']) {
                    $return['deptPercent'][] = $row['total'];
                    $return['deptNumber'][] = substr($row['total'], 0, -1);
                }
            }
        }
        $return['name'] = ['个人进度', '部门进度'];
        $this->ajaxReturn($return);
    }

    /*
     * ajax获取各部门各分类计划百分比（公司领导视图）
     */

    public function getDeptAllPlanPercent() {
        //获取所有部门
        $depts = M('department')->where('dept_name != "公司领导"')->order('dept_no')->select();
        $types = M('plan_type')->where('pid=0')->order('type_no')->select();
        foreach ($types as $t_key => $t_row) {
            foreach ($depts as $key => $row) {
                //获取部门人员
                $deptUsers = M('user')->where('dept_id=' . $row['dept_id'])->getField('user_id', true);
                $tmp = [];
                foreach ($deptUsers as $u_key => $u_row) {
                    $map['sms_flag'] = 0;
                    if (getPlanMode($t_row['type_id']) == 0) {
                        $where['executor'] = array('like', '%' . $u_row . '%');
                    } else {
                        $where['manager'] = $u_row;
                        $where['participator'] = array('like', '%' . $u_row . '%');
                    }
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                    $map['type'] = $t_row['type_id'];
                    $tmp[] = M('work_plan')->field('plan_id,name,manager,participator,executor,type,sms_flag,total_percent')->where($map)->select();
                    $datas[$t_row['type_id']][$row['dept_id']] = $this->array2D($tmp);
                }
            }
        }

        $percents = [];
        foreach ($datas as $key => $type) {
            foreach ($type as $k => $deptarr) {
                if (empty($deptarr)) {
                    $percent = 0;
                } else {
                    $count = count($deptarr);
                    $total = 0;
                    foreach ($deptarr as $row) {
                        $total += $row['total_percent'];
                    }
                    $percent = round($total / ($count * 100) * 100);
                }
                $percents[$key][] = $percent;
            }
        }

        $return['dayPercent'] = $percents[1];
        $return['monthPercent'] = $percents[2];
        $return['yearPercent'] = $percents[7];
        $return['proPercent'] = $percents[11];

//        $return['data'] = $percents;
        $return['type'] = M('department')->where('dept_name != "公司领导"')->order('dept_no')->getField('dept_name', true);
        $return['name'] = M('plan_type')->where('pid=0')->order('type_no')->getField('type_name', true);
        $this->ajaxReturn($return);
    }

    //退出
    public function logout() {
        session(null);
        if (!cookie('username')) {
            setcookie('username', '', 0);
            setcookie('password', '', 0);
        }
        $this->ajaxReturn(array('status' => 1));
    }

    //用户管理列表
    public function user() {
        //获取部门
        $this->depts = M('department')->select();

        if (isset($_GET['dept_id']) && I('dept_id')) {
            $map['dept_id'] = I('dept_id');
            $this->deptId = I('dept_id');
        } else {
            if (isset($_GET['dept_id']) && I('dept_id') == 0) {
                $map['dept_id'] = array('eq', 0);
            } else {
                $map['dept_id'] = array('neq', 0);
        }
        }

        //获取用户
        $p = I('get.p', 1, 'intval');
        $limit = 20;
        $datas = M('user')->field('user_id,user_name,dept_id,user_priv,email,user_priv_name,password,user_priv_no,last_visit_time,openid,head')->where($map)->order('user_no')->page($p, $limit)->select();
        foreach ($datas as $key => $row) {
            if (crypt("", $row['password']) == $row['password']) {
                $datas[$key]['class'] = 'textColor2';
            }
        }
//        print_r($datas);
        $count = M('user')->where($map)->count();
        $this->page = $this->pageLists($count, $limit);
        $this->datas = $datas;
        if (isset($_GET['dept_id'])) {
            $this->del = I('dept_id') == 0 ? 1 : 0;
        }

        $this->display();
    }

    //更新全体用户企业邮箱
    public function updateEmail() {
        //获取企业邮箱id
        $emailLists = getUserExmail();
        foreach ($emailLists as $key => $row) {
            $map['user_name'] = $row['name'];
            $data['email'] = $row['userid'];
            $res = M('user')->where($map)->save($data);
        }
        $this->ajaxReturn(true);
    }

    //清空密码
    public function clearPassword() {
        $user_id = I('id');
        $data['password'] = crypt("");
        $map['user_id'] = $user_id;
        $res = M('user')->where($map)->save($data);
        $return['info'] = $res !== false ? '已清空' : '清空失败';
        $this->ajaxReturn($return);
    }

    //编辑用户
    public function saveUser() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['user_priv'] = $data['priv_id'][0];
            $data['password'] = crypt('');
            unset($data['priv_name']);
            if ($data['user_priv_other']) {
                $data['user_priv_other'] = implode(',', $data['user_priv_other']) . ',';
            }
//            $data = array_change_key_case($data, CASE_UPPER);
            if (I('id')) {
                $map['user_id'] = I('id');
                $res = M('user')->where($map)->save($data);
            } else {
                $res = M('user')->add($data);
            }


            $return['info'] = $res !== false ? '操作成功' : '操作失败';
            $return['url'] = $res !== false ? U('user') : '';
            $this->ajaxReturn($return);
        }

        $user_id = I('id');
        if ($user_id) {
            $info = M('user')->where('user_id="' . $user_id . '"')->find();
            if ($info['user_priv_other']) {
                $info['others'] = explode(',', rtrim($info['user_priv_other'], ','));
            }
            $this->info = $info;
            $this->user_id = I('id');
        }

        //获取部门
        $this->depts = M('department')->select();
        $this->display();
    }

    public function app() {
        $lists = M('web')->select();

        //修改菜单mid
        $this->mid = M('backmenu')->where('name="修改应用"')->getField('id');

        $this->lists = $lists;
        $this->display();
    }

    public function appSave() {
        if (IS_AJAX) {
            $data = I('post.');
            if ($data['id']) {
                $res = M('web')->save($data);
            } else {
                $res = M('web')->add($data);
            }
            if ($res !== false) {
                $return['info'] = '保存成功';
                $return['url'] = U('Index/app');
            }
            $this->ajaxReturn($return);
        }

        if (I('id')) {
            $this->info = M('web')->find(I('id'));
        }
        $this->display();
    }

    public function appDel() {
        $id = I('id');
        $res = M('web')->delete($id);
        if ($res !== false) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //获取首页领导视图的url
    public function getPlanUrl() {
        $type_name = I('type');
        $type = M('plan_type')->where('type_name="' . $type_name . '"')->getField('type_id');

        $dept_name = I('name');
        if ($dept_name == '个人进度') {
            $url = '/index.php/Home/Plan/index/sms_flag/0/pType/' . $type; //sms_falg=0:进行中
        } else {
            if ($dept_name == '部门进度') {
                $dept_id = session('dept_id');
            } else {
                $dept_id = M('department')->where('DEPT_NAME="' . $dept_name . '"')->getField('dept_id');
            }
            $url = '/index.php/Home/Plan/index/sms_flag/0/pType/' . $type . '/to_id/' . $dept_id;
        }

        $this->ajaxReturn($url);
    }

    //删除角色
    public function delRole() {
        $map['user_priv'] = I('id');
        $res = M('user_priv')->where($map)->delete();
        if ($res !== false) {
            $this->ajaxReturn(['info' => '删除成功', 'status' => 1, 'icon' => 6, 'reload' => 1]);
        } else {
            $this->ajaxReturn(['info' => '删除失败', 'status' => 0, 'icon' => 5]);
        }
    }

    //个人设置
    public function accountInfo() {
        if (IS_AJAX) {
            $data = I('post.');
            $birthday = $data['bir_year'] . '-' . $data['bir_mon'] . '-' . $data['bir_day'];
            unset($data['bir_year']);
            unset($data['bir_mon']);
            unset($data['bir_day']);
//            $data = array_change_key_case($data, CASE_UPPER);
            $data['head_url'] = $data['uploads_url'];
            $data['birthday'] = $birthday;
            $res = M('user')->where('user_id = "' . session('user_id') . '"')->save($data);
            if ($res || $res == 0) {
                $return['info'] = '修改成功';
            } else {
                $return['info'] = '修改失败';
            }
            $this->ajaxReturn($return);
        }
        for ($i = 0; $i < 60; $i++) {
            $year[] = $i + 1958;
        }
        for ($i = 0; $i < 12; $i++) {
            $month[] = $i + 1;
        }
        for ($i = 0; $i < 31; $i++) {
            $day[] = $i + 1;
        }
        $userinfo = M('user')->field('user_id,user_name,sex,birthday,add_home,post_no_home,tel_no_home,mobil_no,email,head,head_url')->where('user_id = "' . session('user_id') . '"')->find();
        if ($userinfo['birthday'] != "0000-00-00") {
            $b_year = date("Y", strtotime($userinfo['birthday']));
            $b_month = date("m", strtotime($userinfo['birthday']));
            $b_day = date("d", strtotime($userinfo['birthday']));
            $userinfo['b_year'] = $b_year;
            $userinfo['b_month'] = $b_month;
            $userinfo['b_day'] = $b_day;
            //获取生肖
            $userinfo['zodiac'] = get_animal($b_year);
            //获取星座
            $userinfo['con'] = get_zodiac_sign($b_month, $b_day);
        }
        $this->year = $year;
        $this->month = $month;
        $this->day = $day;
        $this->userinfo = $userinfo;
        $this->display();
    }

    //判断原密码是否正确
    public function checkPass() {
        $pass0 = I('pass0');
        $password = M('user')->where('user_id = "' . session('user_id') . '"')->getField('password');
        $map['password'] = crypt($pass0, $password);
        $row = M('user')->where($map)->find();
        if (!$row) {
            $return['status'] = 1;
            $return['info'] = '原密码填写错误！';
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //修改OA密码
    public function setPass() {
        $data = I('post.');
        $pdata['password'] = crypt($data['pass1']);
        $pdata['last_pass_time'] = date("y-m-d H:i:s");
        $res = M('user')->where('user_id = "' . session('user_id') . '"')->save($pdata);
        if ($res) {
            $return['info'] = '修改密码成功';
        }
        $this->ajaxReturn($return);
    }

    //上传文件
    public function upload() {
        $this->upfile('./Public/Uploads/' . I('fileType') . '/');
    }

    //每十分钟查询数据表,更新未办结流程数
    public function getFlowCount() {
        $count = count($this->getLists(1, 0, 1, ''));
        $this->ajaxReturn($count);
}

    //提出问题与建议
    public function question() {
        $data = I('post.');
        $data['user_id'] = session('user_id');
        $data['create_time'] = time();
        if (I('id')) {
            $data['parent_id'] = I('id');
            unset($data['id']);
        }
        $res = M('advice')->add($data);
        if ($res) {
            $return['info'] = '';
            $return['parent'] = 1;
        } else {
            $return['info'] = '';
        }
        $this->ajaxReturn($return);
    }

    //同步通讯录
    public function updateAddress() {
        //首次全部同步
//        $users = M('user')->field('USER_ID,USER_NAME,USER_NO')->where('DEPT_ID != 0')->select();
//        foreach ($users as $key => $row) {
//            $data['user_id'] = $row['user_id'];
//            $data['address_no'] = $row['user_no'];
//            $res = M('address')->add($data);
//        }
        //单个同步
        $map['user_id'] = I('user_id');
        $user = M('user')->field('user_id,user_name,user_no,dept_id')->where('user_id="' . I('user_id') . '"')->find();
        $row = M('address')->where($map)->find();
        if ($row) {
            if ($user['dept_id'] == 0) {
                //删除通讯录用户
                $res = M('address')->where($map)->delete();
            } else {
                $res = true;
            }
        } else {
            //增加用户
            $data['user_id'] = $user['user_id'];
            $data['address_no'] = $user['user_no'];
            $res = M('address')->add($data);
        }

        $return = $res !== false ? ['status' => 1] : ['status' => 0];
        $this->ajaxReturn($return);
    }

    //通讯录管理
    public function address() {
        $p = I('get.p');
        $limit = $this->limit;

        $map['is_delete'] = 0;

        if (isset($_GET['user_name']) && I('user_name')) {
            $ids = M('user')->where('user_name like "%' . I('user_name') . '%"')->getField('user_id', true);
            $this->name = I('user_name');
        }

        if (isset($_GET['dept_id']) && I('dept_id')) {
            $ids = M('user')->where('dept_id = ' . I('dept_id'))->getField('user_id', true);
            $this->deptid = I('dept_id');
        }
        if (!empty($ids)) {
            if (!is_array($ids)) {
                $ids[] = $ids;
            }
            $map['user_id'] = array('in', $ids);
        }

        $address = M('address')->where($map)->order('address_no')->page($p, $limit)->select();
        foreach ($address as $key => $row) {
            $umap['user_id'] = $row['user_id'];
            $address[$key]['info'] = M('user')->field('user_id,user_name,user_priv,dept_id,sex,birthday,mobil_no,email')->where($umap)->find();
        }
//print_r($map);
        $this->address = $address;

        $count = M('address')->where($map)->count();
        $this->page = $this->pageLists($count, $limit);
        $this->count = $count;

        //获取所有部门
        $this->depts = M('department')->order('dept_no')->select();

        $this->display();
    }

    //编辑联系人
    public function saveAddress() {
        if (IS_AJAX) {
            $data = I('post.');
            if (isset($data['sex'])) {
                $userData['sex'] = $data['sex'];
                M('user')->where('user_id="' . $data['user_id'] . '"')->save($userData);
            }
            $res = M('address')->save($data);

            if ($res !== false) {
                $return = ['info' => '操作成功', 'icon' => 6, 'url' => U('address'), 'status' => 1];
            } else {
                $return = ['info' => '操作失败', 'icon' => 5, 'status' => 0];
            }
            $this->ajaxReturn($return);
        }
        $id = I('id');
        $data = M('address')->find($id);
        $data['info'] = M('user')->where('user_id="' . $data['user_id'] . '"')->find();

        $this->data = $data;
        $this->display();
    }

    //禁用通讯录用户
    public function delAddress() {
        $res = M('address')->delete(I('id'));
        $return = $res !== false ? ['status' => 1] : ['status' => 0];
        $this->ajaxReturn($return);
    }

    //回车查询
    public function enterSearch() {
        $table = I('table');
        $name = I('name');
        if ($name) {
            $map['user_name'] = array('like', '%' . $name . '%');
            $users = M('user')->field('user_id,user_name,mobil_no')->where($map)->select();
        } else {
            $users = [];
        }
        $this->ajaxReturn($users);
    }

    //删除问题与建议
    public function delQuestion() {
        $id = I('id');
        if($id){
            $advice = M('advice')->where('id = '.$id)->find();
            //删除附件
            if ($advice['uploads_url']) {
                $urls = explode(';', rtrim($advice['uploads_url'], ';'));
                foreach ($urls as $url) {
                    @unlink('.' . $url);
                }
            }
            $res = M('advice')->where('id = '.$id.' or parent_id = '.$id)->delete();
            if ($res !== false) {
                $return['info'] = '删除成功';
                $return['reload'] = 1;
            } else {
                $return['info'] = '删除失败';
            }
            $this->ajaxReturn($return);
        }
    }

    //
    public function getCalendar() {
        $start = strtotime(I('date') . ' 00:00:00');
        $end = strtotime(I('date') . ' 23:59:59');
        $map['start_time'] = array('between', [$start, $end]);
        $map['user_id'] = session('user_id');
        $data = M('calendar')->field('id,title,content,remind_time')->where($map)->select();
        foreach ($data as $key => $row) {
            $time = date('m-d H:i', $row['remind_time']);
            $data[$key]['remind_time'] = $time ? $time : I('date');
        }
        $this->ajaxReturn($data);
    }

    //删除用户(离职人员)
    public function delUser() {
        $map['USER_ID'] = I('user_id');
        $res = M('user')->where($map)->delete();

        $return = $res !== FALSE ? ['status' => 1] : ['status' => 0];
        $this->ajaxReturn($return);
    }

    //弹出定时提醒页面
    public function getRemindView() {
        $map['user_id'] = session('user_id');
        $start = time();
        $end = time() + 600;
        $map['remind_time'] = array('between', [$start, $end]);
        $data = M('calendar')->where($map)->select();
        if (!empty($data)) {
            foreach($data as $key=>$row) {
                $data[$key]['remind_time'] = date('m-d H:i',$row['remind_time']);
                $data[$key]['start_time'] = date('Y-m-d',$row['start_time']);
                $data[$key]['end_time'] = date('m-d',$row['end_time']);
            }
        }else{
            $data = [];
        }
        $this->ajaxReturn($data);
    }

}
